package com.qf.cloud2203.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Map;

@Component
public class MyRoutingFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        final Map<String, Object> attributes = exchange.getAttributes();

        final Route route = (Route) attributes.get(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);

        // 从参数中获取代表 微服务名的 参数值
        final ServerHttpRequest request = exchange.getRequest();
        final String servicekey = request.getQueryParams().getFirst("servicekey");

        String serviceUri = getServiceUri(servicekey);

        final URI uri = UriComponentsBuilder.fromUriString(serviceUri).build().toUri();

        final Route newRoute = Route.async()
                .asyncPredicate(route.getPredicate())
                .id(route.getId())
                .filters(route.getFilters())
                .order(route.getOrder())
                .uri(uri)  // 设置新的 url
                .build();
        attributes.put(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR,newRoute);


        return chain.filter(exchange);
    }

    private String getServiceUri(String servicekey) {
        return "lb://SERVICE2";
    }

    @Override
    public int getOrder() {
        return 10;
    }
}
